package dao;

import model.Raider;
import util.ConnMySQL;

import java.sql.*;

public class RaiderDao {
    public RaiderDao(){}

    /**
     * 添加攻略进数据库
     * @param raider
     * @return
     */
    public String addRaider(Raider raider){
        Connection conn = null;
        PreparedStatement preStmt = null;
        ResultSet affectedSet = null;

        String idraider = null;
        try {
            conn = ConnMySQL.getConnection();
            String sql = "insert into raiders(headline, content,publishTime) values(?, ?, ?)";
//			[!]注意这里的insert获取id的写法
            preStmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            preStmt.setString(1,raider.getHeadline());
            preStmt.setString(2,raider.getContent());
            preStmt.setDate(3,raider.getPublishTime());
            preStmt.executeUpdate();
            affectedSet = preStmt.getGeneratedKeys();
            if (affectedSet.next()) {
                idraider = affectedSet.getString(1);
                System.out.println(idraider);
            }
            //user.setIdusers(idusers);
            return idraider;
        } catch  (SQLDataException ex) {
            if (ex.getErrorCode()==1062){
                System.out.println("已经发表");
                return "exist";
            }
            ex.printStackTrace();
            return null;
        }catch (Exception ex){
            ex.printStackTrace();
            return null;
        }finally {
            if (affectedSet != null) {
                try {
                    affectedSet.close();
                    affectedSet = null;
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if (preStmt != null) {
                try {
                    preStmt.close();
                    preStmt = null;
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }
}
